using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Character : MonoBehaviour
{
    public Animator animator;
    public RectTransform imgTrans;
    public RectTransform rootTrans;

    public float baseSpeed = 100;
    public float speedMultiplier = 1;
    public float energy = 0;
    public float maxEnergy = 100;
    public CharacterState state;

    [NonSerialized] public bool isDragging;

    void Start()
    {
        SetState(CharacterState.Idle);
    }

    void OnDestroy()
    {
    }

    void Update()
    {

    }

    public float GetSpeed()
    {
        return isDragging ? 0 : baseSpeed * (0.8f + energy / maxEnergy) * speedMultiplier;
    }

    public void SetScaleMultiplier(float scaleMultiplier)
    {
        rootTrans.localScale = new Vector3(scaleMultiplier, scaleMultiplier, 1);
    }

    public void SetState(CharacterState state)
    {
        if (this.state == state)
        {
            return;
        }
        this.state = state;
        animator.Play(state.ToString());
    }

    public Vector2 GetPosition(){
        return rootTrans.anchoredPosition;
    }

    public void Move(float dt)
    {
        var speed = this.GetSpeed();
        speed = this.isDragging ? 0 : speed;
        var newPos = rootTrans.anchoredPosition + new Vector2(-speed * dt * imgTrans.localScale.x, 0);
        SetPosition(newPos);
    }

    public void SetPosition(Vector2 pos)
    {
        rootTrans.anchoredPosition = pos;
        if (rootTrans.anchoredPosition.x > Screen.width / 2)
        {
            imgTrans.localScale = new Vector3(1, 1, 1);
        }
        else if (rootTrans.anchoredPosition.x < -Screen.width / 2)
        {
            imgTrans.localScale = new Vector3(-1, 1, 1);
        }
    }

    public Vector2 GetScale()
    {
        return new Vector2(imgTrans.localScale.x * rootTrans.localScale.x, imgTrans.localScale.y * rootTrans.localScale.y);
    }

    public void SetScale(Vector2 scale)
    {
        imgTrans.localScale = new Vector3(scale.x, scale.y, 1);
    }

    public void EnableRaycast(bool isEnable)
    {
        animator.GetComponent<Image>().raycastTarget = isEnable;
    }
}

public enum CharacterState
{
    None,
    Idle = 0,
    WakeUp,
    Move,
    Sleep,
}